﻿using Microsoft.Extensions.Options;
using RuoVea.ExSugar;
using RuoVea.ExSugar.FulLog;
using RuoVea.ExUtil;
using RuoVea.OmiApi.Log.Entitys;
using SqlSugar;

namespace RuoVea.OmiApi.Log;

/// <summary>
/// 数据库相关日志记录
/// </summary>
public class ICustomizeSqlSugarLog : RestFulLog, IRestFulLog
{
    /// <summary>
    /// 数据库上下文
    /// </summary>
    public readonly SqlSugarScope dbContext;
    private readonly List<DbConnectionConfig> _dbConnection;

    /// <summary>
    /// 
    /// </summary>
    public ICustomizeSqlSugarLog(IOptions<List<DbConnectionConfig>> dbConnection)
    {
        _dbConnection = ExSugar.Util.SugarUtil.GetDbConfig(dbConnection.Value);
        dbContext = ExSugar.Util.SugarUtil.GetSqlSugarScope(_dbConnection);
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="dbType"></param>
    /// <param name="diffLogData"></param>
    public override void DiffLog(DbType dbType, DiffLogModel diffLogData)
    {
        base.DiffLog(dbType, diffLogData);
    }
    /// <summary>
    /// 差异日志 不会记录日志相关信息差异
    /// </summary>
    /// <param name="afterData"></param>
    /// <param name="beforeData"></param>
    /// <param name="parameters"></param>
    /// <param name="sql"></param>
    /// <param name="time"></param>
    /// <param name="businessData"></param>
    /// <param name="diffType"></param>
    /// <param name="elapsed"></param>
    public override void DiffLogString(List<DiffLogTableInfo> afterData, List<DiffLogTableInfo> beforeData, SugarParameter[] parameters, string sql, TimeSpan? time, object businessData, DiffType diffType, long elapsed)
    {
        // 移除相同字段
        for (int i = 0; i < afterData.Count; i++)
        {
            var afterColumns = afterData[i].Columns;
            var beforeColumns = beforeData[i].Columns;
            for (int j = 0; j < afterColumns.Count; j++)
            {
                if (afterColumns[j].Value.Equals(beforeColumns[j].Value))
                {
                    beforeColumns.Remove(beforeColumns[j]);
                    afterColumns.Remove(afterColumns[j]);
                    j--;
                }
            }
        }

        dbContext.Insertable(new SysLogDiff
        {
            AfterData = afterData?.Json2Str(),
            BeforeData = beforeData?.Json2Str(),
            BusinessData = businessData?.Json2Str(),
            DiffType = diffType.ToString(),
            Elapsed = elapsed,
            Sql = sql,
            Parameters = parameters?.Json2Str(),
            CreateTime = DateTime.Now
        }).ExecuteCommand();
    }
}
